package com.bilibili.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;
import java.util.Set;

/**
 * Redis的操作工具类
 */
@Component
public class RedisOperations {
    @Autowired
    private JedisPool jedisPool;
    private static final String REDIS_OK_STR = "OK";

    @FunctionalInterface
    interface RedisCallback<T> {
        T execute(Jedis jedis);
    }

    private <T> T execute(RedisCallback callback) {
        try (Jedis jedis = jedisPool.getResource()) {
            return (T) callback.execute(jedis);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("服务器异常");
        }
    }

    public boolean set(String key, String value) {
        return execute(jedis -> StringUtils.equals(REDIS_OK_STR, jedis.set(key, value)));
    }

    public boolean set(String key, Object value) {
        return execute(jedis -> StringUtils.equals(REDIS_OK_STR, jedis.set(key, JSON.toJSONString(value))));
    }

    public long expire(String key, int seconds) {
        return execute(jedis -> jedis.expire(key, seconds));
    }

    public String get(String key) {
        return execute(jedis -> jedis.get(key));
    }

    public boolean del(String key) {
        return execute(jedis -> jedis.del(key) > 0);
    }

    public Set<String> zrevrange(String key, long start, long stop) {
        return execute(jedis -> jedis.zrevrange(key, start, stop));
    }

    public Set<String> zincrby(String key, Double score, String member) {
        return execute(jedis -> jedis.zincrby(key, score, member));
    }

    public boolean zadd(String key, Map<String, Double> scoreMembers) {
        return execute(jedis -> jedis.zadd(key, scoreMembers));
    }

    public boolean exists(String key) {
        return execute(jedis -> jedis.exists(key));
    }


}
